import {
  getApiBaseUrl,
  getUploadUrl,
  getConvertUrl,
  getDownloadUrl,
  buildApiUrl,
} from "../config/index.js";

// 通用请求函数
const request = async (url, options = {}) => {
  const defaultOptions = {
    headers: {
      "Content-Type": "application/json",
    },
    ...options,
  };

  let finalUrl = url;

  // 如果是GET请求且有params，则构建查询字符串
  if (
    (!options.method || options.method.toUpperCase() === "GET") &&
    options.params
  ) {
    const query = new URLSearchParams(options.params).toString();
    finalUrl = `${url}?${query}`;
    delete defaultOptions.params; // 从fetch的options中移除，因为它不是标准属性
  }

  try {
    const response = await fetch(finalUrl, defaultOptions);

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("API请求失败:", error);
    throw error;
  }
};

// 文件上传请求函数
const uploadFile = async (url, formData) => {
  try {
    const response = await fetch(url, {
      method: "POST",
      body: formData,
      // 不设置Content-Type，让浏览器自动设置multipart/form-data
    });

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    return await response.json();
  } catch (error) {
    console.error("文件上传失败:", error);
    throw error;
  }
};

// WebP转换相关API
export const webpApi = {
  // 获取API基础URL
  getBaseUrl: async () => getApiBaseUrl(),

  // 上传图片
  upload: async (formData) => uploadFile(await getUploadUrl(), formData),

  // 转换图片
  convert: async (data) =>
    request(await getConvertUrl(), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }),

  // 下载文件
  download: async (filename) => `${await getDownloadUrl()}/${filename}`,

  // 获取转换状态
  getStatus: async (taskId) => request(await buildApiUrl(`/status/${taskId}`)),

  // 获取转换历史
  getHistory: async () => request(await buildApiUrl("/history")),

  // 删除文件
  deleteFile: async (filename) =>
    request(await buildApiUrl(`/delete/${filename}`), {
      method: "DELETE",
    }),
};

// 时间戳转换相关API
export const timestampApi = {
  // 转换时间戳
  convert: async (data) =>
    request(await buildApiUrl("/api/timestamp/convert"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }),
};

// API测试相关API
export const apiTestApi = {
  // 发送测试请求
  test: async (data) =>
    request(await buildApiUrl("/api/test"), {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
    }),
};

// 通用API
export const commonApi = {
  // 健康检查
  health: async () => request(await buildApiUrl("/health")),

  // 获取服务器信息
  info: async () => request(await buildApiUrl("/info")),

  // 站点状态检查
  checkUrl: async (url) =>
    request(await buildApiUrl("/api/check-url"), {
      method: "GET",
      params: { url },
    }),

  // 获取汇率
  getExchangeRate: async () => {
    const url =
      "https://wise.com/rates/history+live?source=AUD&target=CNY&length=30&resolution=hourly&unit=day";
    const response = await request(await buildApiUrl("/api-proxy"), {
      method: "POST",
      body: JSON.stringify({
        url,
        method: "GET",
        headers: {
          Accept: "application/json",
          "User-Agent":
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        },
      }),
    });

    // 处理返回的数据
    if (response && response.body && Array.isArray(response.body)) {
      const latestRate = response.body[response.body.length - 1];
      return {
        success: true,
        rate: latestRate.value,
        date: new Date(latestRate.time).toISOString(),
        history: response.body,
      };
    }

    throw new Error("无效的汇率数据");
  },
};
